package com.lovi.admin.controller;

import com.lovi.admin.service.ProductService;
import com.lovi.admin.utils.AliyunOSSUtils;
import com.lovi.param.ProductSaveParam;
import com.lovi.param.ProductSearchParam;
import com.lovi.pojo.Product;
import com.lovi.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 *  商品后台管理controller
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Value("${upload.imagePath}")
    private String basePath;
    @Value("${upload.imageUrl}")
    private String imgUrl;

    @Autowired
    private ProductService productService;

    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;

    @GetMapping("list")
    public R  adminList(ProductSearchParam productSearchParam){

        return productService.search(productSearchParam);
    }

    @PostMapping("upload")
    public R  adminUpload(@RequestParam("img") MultipartFile img) throws Exception {

        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(img.toString());
        //原始文件名
        String originalFilename = img.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复照成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //新建一个目录对象
        File dir = new File(basePath);

        //判断转存的目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            img.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里我们返回的是图片的网络路径，就是感觉url可以直接访问那种
        //网络前缀

        return R.ok("图片上传成功!",imgUrl+fileName);
    }


    @PostMapping("save")
    public R adminSave(ProductSaveParam productSaveParam){

        return productService.save(productSaveParam);
    }

    @PostMapping("update")
    public R adminUpdate(Product product){

        return productService.update(product);
    }

    @PostMapping("remove")
    public R adminRemove(Integer productId){

        return productService.remove(productId);
    }
}
